package com.jiaxu.qqmusic;


import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.os.Handler;
import android.os.IBinder;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

public class MainActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener, AdapterView.OnItemClickListener {
    public static final int PLAY = 1;
    public static final int PAUSE = 0;
    public static final int CHANGE = 2;
    public static final String TAG = "tagg";
    private SeekBar seekBar;
    private TextView t1;
    private TextView t2;
    private TextView artist;
    private TextView title;
    private ListView list;
    public MyService.Mybinder binder;
    Handler handler = new Handler();
    private int userChanged = 0;
    private int progress;
    private int position;
    Mp3Info mp3Info;
    SimpleAdapter mAdapter;
    List<Mp3Info> mp3Infos; //歌曲信息集合

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        seekBar = (SeekBar) findViewById(R.id.bar);
        t1 = (TextView) findViewById(R.id.startTime);
        t2 = (TextView) findViewById(R.id.endTime);
        artist = (TextView) findViewById(R.id.atrist);
        title = (TextView) findViewById(R.id.title);
        list = (ListView) findViewById(R.id.face);
        Intent intent = new Intent("musicservice");
        startService(intent);

        bindService(intent, new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder proxy) {
                binder = (MyService.Mybinder) proxy;
                handler.post(update); //启动update线程
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                binder = null;
            }
        }, BIND_AUTO_CREATE);

        seekBar.setOnSeekBarChangeListener(this);
        list.setOnItemClickListener(this);
//-------------------------------初始化适配器和播放列表-----------------------------------
        mp3Infos = new MediaUtils(this).getMp3Infos();
        setListAdpter(mp3Infos);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(update);//退出时销毁线程
    }

    public void play(View view) {
        Intent intent = new Intent("musicservice");
        intent.putExtra("action", PLAY);
        startService(intent);
    }

    public void Stop(View view) {
        Intent intent = new Intent("musicservice");
        intent.putExtra("action", PAUSE);
        startService(intent);
    }

    //---------------------------从服务更新歌曲进度和播放时间，的线程（循环执行）-------------------------------------
    Runnable update = new Runnable() {
        @Override
        public void run() {
            switch (userChanged) {
                case 0: //自动读条状态
                    seekBar.setMax(binder.getDuration());
                    seekBar.setProgress(binder.getProgress());
                    t1.setText(FormatTime.formatTime(binder.getProgress()));
                    t2.setText(FormatTime.formatTime(binder.getDuration()));
                    if (mp3Info != null) {
                        artist.setText(mp3Info.getArtist() + "");
                        title.setText(mp3Info.getTitle() + "");
                    }
                    break;
                case 1:  //按下待命状态
                    t1.setText(FormatTime.formatTime(progress));
                    break;
                case 2:  // 跳转进度并回到自动读条状态
                    binder.setProgress(progress);
                    userChanged = 0;
                    break;
            }
            handler.postDelayed(update, 0); //循环update线程
        }
    };

    //-----------------------------设定进度条监听器动作------------------------------------
    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (fromUser == true) {
            this.progress = progress;
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        userChanged = 1;
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        userChanged = 2;
    }


    public void setListAdpter(List<Mp3Info> mp3Infos) {
        List<HashMap<String, String>> mp3list = new ArrayList<HashMap<String, String>>();
        for (Iterator iterator = mp3Infos.iterator(); iterator.hasNext(); ) {
            Mp3Info mp3Info = (Mp3Info) iterator.next();
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("title", mp3Info.getTitle());
            map.put("Artist", mp3Info.getArtist());
            map.put("duration", FormatTime.formatTime(mp3Info.getDuration()));
            map.put("size", String.valueOf(mp3Info.getSize()));
            map.put("url", mp3Info.getUrl());
            mp3list.add(map);
        }
        //----------------------------SimpleAdapter模式的使用------------------------------------------------
        mAdapter = new SimpleAdapter(this, mp3list,
                R.layout.itme, new String[]{"title", "Artist", "duration"},
                new int[]{R.id.music_title, R.id.music_Artist, R.id.music_duration});
        list.setAdapter(mAdapter);
    }

    // ---------------------------------------ListView 设定监听器动作-----------------------------------
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (mp3Infos != null) {
            this.position = position;
            mp3Info = mp3Infos.get(position);
            Intent intent = new Intent("musicservice");
            intent.putExtra("action", CHANGE);
            intent.putExtra("url", mp3Info.getUrl());
            startService(intent);
        }
    }
}
